<template>
	<view class="modify-page">
		
		<form class="loginForm" :model="userDetails" @submit="onSubmit">
			<!-- 头像 -->
			<view class="avatar-section">
				<image class="avatar-img" :src="userDetails.avatar" mode="aspectFill" />

				<text class="avatar-tip" @click="handleUpload">更换头像</text>
			</view>

			<!-- 信息表单 -->
			<view class="info-list">
				<view class="info-item">
					<text class="item-label">昵称</text>
					<input class="item-input" type="text" v-model="userDetails.nickname" placeholder="请输入昵称" />
				</view>
				<!-- <view class="info-item">
					<text class="item-label">微信</text>
					<input class="item-input" type="text"  placeholder="请输入微信号" />
				</view> -->
				<view class="info-item">
					<text class="item-label">支付宝</text>
					<input class="item-input" type="text" v-model="userDetails.alipay_account" placeholder="请输入支付宝账号" />
				</view>
			</view>

			<!-- 占位区块 -->
			<view class="bottom-block"></view>

			<!-- 确定按钮 -->
			<view class="submit-btn-box">
				<button class="submit-btn" @click="onSubmit">确定</button>
			</view>

		</form>
	</view>
</template>

<script setup>
	import { ref,reactive } from "vue"
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { Config } from '@/utils/config.js';
	import { updataMember } from '@/api/member.js';
	import { useUserStore } from '@/store/userStore';
	const userStore = useUserStore();
	const userDetails = reactive({
		avatar: userStore.userDetails?.avatar || '',
		nickname: userStore.userDetails?.nickname || '',
		card: userStore.userDetails?.card || '',
		alipay_account: userStore.userDetails?.alipay_account || '',
		realname:userStore.userDetails?.realname || ''
	});
	
	const previewUrl = ref('');   // 预览图地址
	const uploading = ref(false); // 上传状态
	const progress = ref(0);      // 上传进度

	// 选择图片
	const handleUpload = async () => {
	  try {
	    // 1. 选择图片
		const res = await uni.chooseImage({
		  count: 1, // 关键参数：限制1张
		  sizeType: ['compressed'],
		  sourceType: ['album', 'camera']
		});
	    console.error('显示预览:', res.tempFilePaths[0]);
	    // 2. 显示预览
	    userDetails.avatar = res.tempFilePaths[0];

	    // 3. 执行上传
	    uploading.value = true;
	    const uploadRes = await uploadFile(res.tempFilePaths[0]);
	    console.error('执行上传:', uploadRes);
	    // 4. 处理结果
	    console.log('服务器返回:', uploadRes);
	    uni.showToast({ title: '上传成功' });
	    userDetails.avatar = uploadRes.data
		userStore.updateUserDetails(userDetails);
	  } catch (err) {
	    console.error('上传失败:', err);
	    uni.showToast({ title: '上传失败', icon: 'error' });
	  } finally {
	    uploading.value = false;
	  }
	};

	// 封装上传方法
	const uploadFile = (filePath) => {
	  return new Promise((resolve, reject) => {
	    const task = uni.uploadFile({
	      url: Config.restUrl+'/upload',
	      filePath,
	      name: 'file',
	      header: { 'Authorization': uni.getStorageSync("token") },
	      success: (res) => {
	        if (res.statusCode === 200) {
	          resolve(JSON.parse(res.data));
	        } else {
	          reject(new Error(`服务器错误: ${res.statusCode}`));
	        }
	      },
	      fail: reject
	    });
	    // 进度监听
	    task.onProgressUpdate((e) => {
	      progress.value = e.progress;
	    });
	  });
	};

	const onSubmit = async()=>{
		let result = await updataMember(userDetails).then(res=>{
			uni.showToast({ title: '更新成功', icon: 'success' });
      userStore.updateUserDetails(userDetails);
      setTimeout(() => {
        goBack();
      }, 2000);
		})
	}
  function goBack() {
    //uni.navigateBack()
	uni.navigateBack({
	    success: () => {
	      const pages = getCurrentPages();
	      const prevPage = pages[pages.length - 1]; // 获取上一页实例
	      if (prevPage && prevPage.$vm.onShow) {
	        prevPage.$vm.onShow(); // 强制刷新上一页
	      }
	    }
	  });
  }
</script>

<style scoped>
.modify-page {
	min-height: 100vh;
	background: #f6f7fb;
	display: flex;
	flex-direction: column;
}
.avatar-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-top: 40rpx;
	margin-bottom: 24rpx;
}
.avatar-img {
	width: 140rpx;
	height: 140rpx;
	border-radius: 50%;
	background: #4a90e2;
}
.avatar-tip {
	color: #bbb;
	font-size: 24rpx;
	margin-top: 16rpx;
}
.info-list {
	background: #fff;
	border-radius: 0 0 20rpx 20rpx;
	margin-bottom: 32rpx;
	margin-top: 2rpx;
}
.info-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 32rpx;
	height: 90rpx;
	border-bottom: 2rpx solid #f2f2f2;
}
.info-item:last-child {
	border-bottom: none;
}
.item-label {
	font-size: 28rpx;
	color: #222;
	width: 120rpx;
}
.item-input {
	flex: 1;
	text-align: right;
	font-size: 26rpx;
	color: #222;
	border: none;
	background: transparent;
	outline: none;
}
.bottom-block {
	flex: 1;
	background: #f6f7fb;
}
.submit-btn-box {
	position: fixed;
	left: 0;
	bottom: 0;
	width: 100vw;
	background: transparent;
	z-index: 99;
	padding-bottom: env(safe-area-inset-bottom);
}
.submit-btn {
	width: 100vw;
	height: 90rpx;
	background: #4a90e2;
	color: #fff;
	font-size: 32rpx;
	border-radius: 0;
	border: none;
	margin: 0;
	font-weight: bold;
}
.back-icon image{
	width: 40rpx;
	height: 40rpx;
}
</style>
